<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\WaterStorageOut;
use App\Models\WaterMyStorage;
use DB;

class WaterStorageOutController extends Controller {

    protected $message = [
        'name.required' => '商品名称必须',
        'name.max' => '商品名称不能超过100个字符',
        'company_id.required' => '项目必须',
        'company_id.integer' => '项目格式为整数值',
        'company_id.exists' => '项目不存在',
        'site_id.required' => '站点必须',
        'site_id.integer' => '站点格式为整数值',
        'site_id.exists' => '站点不存在',
        'shops.array' => "商品参数错误",
        'shops.min' => "至少选择一个商品",
        'shops.*.out_num.required' => '出库数量必须',
        'shops.*.out_num.integer' => '出库数量格式为整数值',
        'shops.*.out_num.lte' => '出库数量必须小于等于库存',
    ];

    /**
     * 出库库单列表
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request) {
        $perPage = $request->input('pageSize', 15);
        $query = WaterStorageOut::query();
        $cid = $request->input('company', '');
        if (!empty($cid)) {
            $query->where('company_id', $cid);
        }
        $sid = $request->input('site', '');
        if (!empty($sid)) {
            $query->where('site_id', $sid);
        }

        $status = $request->input('status', '');
        if (trim($status) !== "") {
            $query->where('status', $status);
        }

        $created = $request->input('created_at', []);
        if (!empty($created)) {
            $query->whereBetween('created_at', $created);
        }

        $query->with([
            'companies' => function($query) {
                $query->select(['Co_ID', 'Co_Name']);
            },
            'sites' => function($query) {
                $query->select(['id', 'name']);
            },
            'shops.shop' => function($query) {
                 $query->select(['id', 'name', "unit"]);
            },
        ]);
        $list = $query->paginate($perPage);
        return $list;
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create() {
        //
    }

    /**
     * 添加入库单.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request) {
        // $data = $request->input();

        $data = $this->validateData($request);
        $user = $request->user();
        $data['creater_uid'] = $user->userid;
        $data['creater_name'] = $user->username;
        $shops = $data['shops'];
        unset($data['shops']);
        
        DB::beginTransaction();
        $ret = WaterStorageOut::create($data);
        $attachData = collect($shops)->map(function($item) {
                    return collect($item)->only(['out_num', 'id']);
                })
                ->keyBy('id')
                ->map(function($item) {
            return collect($item)->except(['id'])->all();
        });
        
        $ret->shops()->attach($attachData->all());
        $inputs = [
            'company_id'=>$ret->company_id,
            'site_id'=>$ret->site_id,
        ];
        $updated = $this->updateMyStorage($inputs, $attachData);
        if(!$updated) {
             DB::rollback();
             $this->error('保存出库单失败');
        }else{
            DB::commit();
        }

        
        // $ret->shops()->save();
        if (!$ret) {
            $this->error('保存出库单失败');
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id) {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id) {
        //
    }

    /**
     * 更新入库单.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id) {
        // $data = $request->input();

        $data = $this->validateData($request, $id);

        $ws = WaterStorageOut::find($id);

        $shops = $data['shops'];

        $pivotData = collect($shops)->map(function($item) {
                    return collect($item)->only(['out_num', 'id']);
                })
                ->keyBy('id')
                ->map(function($item) {
            return collect($item)->except(['id'])->all();
        });
        $ret = $ws->update($data);
        if ($ret) {
            $ws->shops()->sync($pivotData->all());
        }
        if (!$ret) {
            $this->error('保存失败');
        }
    }

    //验证表单
    protected function validateData($request, $id = false) {

        $rules = [
            'shops' => ["array", "min:1"],
            'shops.*.out_num' => 'required|integer|lte:shops.*.num',
        ];


        $v = $this->validate2($request, $rules, $this->message);

        $user = $request->user();
        $isSuper = $user->isSuper();
        $isSuperAdmin = $user->isSuperAdmin();

        $v->sometimes('company_id', 'required|integer|exists:t_companycnfo,Co_ID', function()use($isSuper) {
            return $isSuper;
        });

        $v->sometimes('site_id', 'required|integer|exists:sites,id', function()use($isSuperAdmin) {
            return $isSuperAdmin;
        });
        $data = $request->input();
        if (!$isSuper) {
            $data['company_id'] = $user->Co_ID;
        }
        if (!$isSuperAdmin) {
            $data['site_id'] = $user->scope;
        }

        $v->validate();
        return $data;
    }

    /**
     * 删除入库单
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id) {
        $ws = WaterStorageOut::findOrFail($id);
        if (!$ws->delete()) {
            $this->error('删除失败');
        }
    }


    //更新库存
    protected function updateMyStorage($inputs, $data) {
        $flag = true;
        DB::beginTransaction();
        $data->each(function($item, $index) use($inputs, &$flag) {
            $sid = $index;
            $num = data_get($item, 'out_num', 0);
            $find = WaterMyStorage::find($sid);
            $snum = $find->num;
            if($num==0||$num>$snum) {
                $flag = false;
                DB::rollBack();
                return false;
            }
            $find->decrement('num', $num);
        });
        if($flag) {
            DB::commit();
        }
        return $flag;
    }

}
